﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Text;
using AMS.Core.Entities;
using AMS.WorkBill.DataAccess;
using AMS.WorkBill.Entities;
using AMS.WorkBill.Manager;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Web.UI;

namespace AMS.Web.WorkBill
{
    public partial class WoAssetInfoSelectedCtl : System.Web.UI.UserControl
    {
        private BaseDataAccess m_Acc = new BaseDataAccess();
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private WoPageBuilder m_WoPageBuilder;
        private PageBuilder m_PageBuilder;
        private Page m_Page;

        public PageBuilder CurrPageBuilder
        {
            get { return m_PageBuilder; }
        }

        public Page CurrPage
        {
            get { return m_Page; }
        }
        private UserDataSourceBuilder DataSourceBuilder
        {
            get { return (UserDataSourceBuilder)Session["DataSourceBuilder"]; }
            set { Session["DataSourceBuilder"] = value; }
        }

        public string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\WoSetting.xml"; }
        }

        public string MenuId
        {
            get { return Request.QueryString["MenuId"]; }
        }

        public string ClassName
        {
            get { return hdnClassName.Value; }
            set { hdnClassName.Value = value; }
        }

        public string TypeName
        {
            get { return hdnTypeName.Value; }
            set { hdnTypeName.Value = value; }
        }

        public string WoIdVal
        {
            get { return hdnKeyVal.Value; }
            set { hdnKeyVal.Value = value; }
        }

        public string WoCode
        {
            get { return hdnWoCode.Value; }
            set { hdnWoCode.Value = value; }
        }

        private string QueryCondition
        {
            get
            {
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }

        private string ReturnQueryStringValue(string keyString)
        {
            string strValue = Request.QueryString[keyString];
            if (strValue == null)
                strValue = "";
            return Convert.ToString(strValue);
        }

        private XmlNode GetListSqlSettingNode()
        {
            return
                m_WoPageBuilder.CurrPageBuilder.m_LoadHelper.XmlReader.GetXmlNode("Setting/" + ClassName + "/" + TypeName +
                                                                "/commandSetting/SelectedListSql");
        }

        private string GetListSql()
        {
            XmlNode sqlSettingNode = GetListSqlSettingNode();
            return m_WoPageBuilder.CurrPageBuilder.GetNodeAttributeValue(sqlSettingNode, m_WoPageBuilder.CurrPageBuilder.m_LoadHelper.SQL, true);
        }


        protected override void OnInit(EventArgs e)
        {
            ClassName = ReturnQueryStringValue("ClassName");
            TypeName = ReturnQueryStringValue("TypeName");
            if (m_WoPageBuilder == null)
                m_WoPageBuilder = new WoPageBuilder(Page, SettingXmlPath);
            if (TypeName.Length > 0)
            {
                XmlNode listSqlNode = GetListSqlSettingNode();
                if (listSqlNode != null)
                {
                    m_WoPageBuilder.CurrPageBuilder.SetPgListAttribute(pgList, listSqlNode, true, true, false);
                    m_WoPageBuilder.SetCommandSetTableInfo(tblWoSetProInfo, ClassName, TypeName);
                }
            }
            base.OnInit(e);
        }

        public void SetData()
        {
            m_WoPageBuilder.SetTableData(tblWoSetProInfo,ClassName,TypeName,this);
            btnUpdate.Visible = (tblWoSetProInfo != null && tblWoSetProInfo.Controls.Count > 0);
            btnUpdateList.Visible = (tblWoSetProInfo != null && tblWoSetProInfo.Controls.Count > 0);
            if(m_WoPageBuilder.WoIsClose())
            {
                btnDelete.Enabled = false;
                btnExec.Enabled = false;
                btnUpdate.Enabled = false;
                btnUpdateList.Enabled = false;
                if (tblWoSetProInfo != null) tblWoSetProInfo.Visible = false;
                tblError.Visible = false;
            }
            pgList.BindGrid();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            pgError.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindPgError);
            if (!IsPostBack)
            {
                m_CreateCtlHlp.SetDdlCondition(pgList, ddlCondition);
                SetData();
               
            }
        }

        private UserDataSourceBuilder BindPgList()
        {
            string sql = GetListSql();
            sql = sql.Replace("\r\n", " ").Replace("\t", " ");
            if (sql.IndexOf("{0}") > -1)
                sql = sql.Replace("{0}", WoCode);
            sql += " " + QueryCondition;
            DataSourceBuilder = new UserDataSourceBuilder(sql, pgList);
            return DataSourceBuilder;
        }

        private object BindPgError()
        {
            object obj = m_WoPageBuilder.GetExecErrMsg();
            pgError.Visible = obj != null;
            return m_WoPageBuilder.GetExecErrMsg();
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (ConditionSelector1.SelectedConditionString.Length > 0)
                QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            pgList.BindGrid();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            pgList.BindGrid();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            WorkBillManager manager = new WorkBillManager();
            string strIds = pgList.GetSelectedItem(1);
            if(strIds.Length==0)
            {
                Alert.MessageBox("请选择删除的记录");
                return;
            }
            manager.DeleteWoCommands(pgList.GetSelectedItem(1));
            Alert.MessageBox("删除成功");
            pgList.BindGrid();
        }

        private void UpdateAssetInfos(StringCollection scIds)
        {
            //var access = 0;
            //var saveHelper = new WoSaveHelper(Page, SettingXmlPath);
            //var sb = new StringBuilder();
            //try
            //{
            //    var i = 0;
            //    var sql = saveHelper.GetUpdateField(ClassName, TypeName, this);
            //    int index = sql.LastIndexOf(',');
            //    sql = sql.Substring(0, index);
            //    foreach (var id in scIds)
            //    {
            //        i++;
            //        var updateSql = sql + " where Id ='" + id + "';";
            //        sb.Append(updateSql);
            //        if (i % 100 == 0 || i == scIds.Count - 1)
            //        {
            //            access = m_Acc.ExecuteCmd(sb.ToString());
            //            sb = new StringBuilder();
            //        }
            //        //access = m_Acc.ExecuteCmd(sql);
            //    }
            //}
            //catch (Exception ex)
            //{

            //    throw;
            //}

            //if (access > 0)
            //    Alert.MessageBox("更新成功!");
            //pgList.BindGrid();

            var acc = new WorkBillAccess();
            var saveHelper = new WoSaveHelper(Page, SettingXmlPath);
            var scErrInfo = new StringCollection();
            acc.BeginTransaction();
            try
            {
                saveHelper.UpdateWoCommand(scIds, typeof(WoCommand), ClassName, TypeName, acc, this, ref scErrInfo);
                m_WoPageBuilder.SetExecErrMsg(scErrInfo);
                acc.Commit();
            }
            catch (Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }
            pgList.BindGrid();
            pgError.Visible = (scErrInfo.Count > 0);
            if (pgError.Visible)
                pgError.BindGrid();
            else
            {
                Alert.MessageBox("更新成功!");
            }
        }

        private void UpdateAssetInfos(string woCode)
        {
            WorkBillAccess acc = new WorkBillAccess();
            WoSaveHelper saveHelper = new WoSaveHelper(Page, SettingXmlPath);
            StringCollection scErrInfo = new StringCollection();
            acc.BeginTransaction();
            try
            {
                saveHelper.UpdateWoCommand(woCode, typeof(WoCommand), ClassName, TypeName, acc, this, ref scErrInfo);
                m_WoPageBuilder.SetExecErrMsg(scErrInfo);
                acc.Commit();
            }
            catch (Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }
            pgList.BindGrid();
            pgError.Visible = (scErrInfo.Count > 0);
            if (pgError.Visible)
                pgError.BindGrid();
        }

   

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            var saveHelper = new WoSaveHelper(Page, SettingXmlPath);
            string strIds = pgList.GetSelectedItem(1);
            if(string.IsNullOrEmpty(strIds))
            {
                Alert.MessageBox("没有选择资产!");
                return;
            }
     
            var scIds = saveHelper.ConvertToStringCollection(strIds);
            UpdateAssetInfos(scIds);
            Alert.MessageBox("更新成功！");
            pgList.BindGrid();
        }

        private void SetImportCtlDisabled()
        {
            object obj = Page.FindControl("ctlImportor");
            if(obj != null && obj is WoCommandImportorCtl)
            {
                ((WoCommandImportorCtl)obj).Visible = false;
            }
        }
        

        protected void btnExec_Click(object sender, EventArgs e)
        {
            var manager = new WorkBillManager();
            var woInfo = manager.GetWoInfo(WoCode);
            var acc = new WorkBillAccess();
            var saveHelper = new WoSaveHelper(Page, SettingXmlPath);
            if(woInfo==null)
            {
                Alert.MessageBox("工单对象为空");
                return;
            }
            StringCollection scErr=null;
            acc.BeginTransaction();
            try
            {
                
                saveHelper.ExceWoCommand(woInfo, ClassName, TypeName, acc, out scErr);
                if (scErr != null && scErr.Count > 0)
                {
                    
                    acc.RollBack();
                }
                else
                {
                    acc.Commit();
                    if (TypeName == "Borrow" || TypeName == "Maintain")
                    {
                        UpdateAssetInfoState(WoCode,TypeName);
                    }
                    m_WoPageBuilder.SetCurrSessionWoInfo(Page, woInfo);
                }

            }
            catch(ArgumentException aex)
            {
                acc.RollBack();
                Alert.MessageBox(aex.Message);
                return;
            }
            catch (Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }
            if(scErr!=null && scErr.Count > 0)
            {
                m_WoPageBuilder.SetExecErrMsg(scErr);
                pgError.BindGrid();
                pgError.Visible = true;
                Alert.MessageBox("执行失败，详细信息见下面错误列表！");
            }
            else
            {
                m_WoPageBuilder.SetExecErrMsg(null);
                pgError.Visible = false;
                Alert.MessageBox("执行成功");
                SetImportCtlDisabled();
                m_WoPageBuilder.SetCurrSessionWoInfo(Page, woInfo);
                SetData();
            }
            
            pgList.BindGrid();
        }

        private void UpdateAssetInfoState(string woCode,string typeName)
        {
            var acc = new WorkBillAccess();
            acc.BeginTransaction();
            try
            {
                NameObjectDictionary ndCommSet = acc.GetObjectsByKeyValues(typeof(WoCommand).Name, "Id", "WoCode", new StringCollection { woCode });
                var aliasValue = typeName == "Borrow" ? "lend" : "service";
                var stateList = acc.GetObjectList(new AssetState().GetType().Name, "Alias", aliasValue);
                if (stateList != null && stateList.Count > 0)
                {
                    var currentState = (AssetState)stateList[0];

                    foreach (var set in ndCommSet)
                    {
                        IList objList = acc.GetObjectList(new WoCommand().GetType().Name, "Id", set.ToString());
                        var currentWoCommand = (WoCommand)objList[0];
                        var currentAssetInfo = currentWoCommand.AssetInfo;
                        currentWoCommand.TargetState = currentState;
                        currentAssetInfo.State = currentState;
                        acc.SaveOrUpdate(currentWoCommand);
                        acc.SaveOrUpdate(currentAssetInfo);
                    }
                }
                var dt =
                    m_Acc.GetDataTableBySql(
                        @"select air.HId from dbo.AmsHistory_AssetInfoRecord air 
join dbo.AmsHistory_HisVersionInfo hvi on air.HVersionId = hvi.Id join dbo.AmsWorkBill_WoInfo wo on hvi.WoInfoId = wo.Id
 where wo.TypeName='" + typeName + "' and wo.Code='" + woCode  + "'");
                if(dt != null && dt.Rows.Count > 0)
                {
                    string idList = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        idList += "'" + dt.Rows[i][0] + "',";
                    }
                    idList = idList.Substring(0, idList.Length - 1);
                    var updateSql = "Update AmsHistory_AssetInfoRecord set StateId= (select Id from dbo.AmsCore_AssetState where Alias='" + aliasValue + "') where HId in (" + idList + ")";
                    m_Acc.ExecuteCmd(updateSql);

                    
                }

                acc.Commit();
               
            }
            catch (Exception)
            {
                acc.RollBack();
                throw;
            }
           
        }

        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
            m_WoPageBuilder.ShowAssetInfoByWoCommandId(e.SelectedDataKeyValue, Page);
        }

        protected void btnUpdateList_Click(object sender, EventArgs e)
        {
            if (DataSourceBuilder == null || DataSourceBuilder.PrimaryKeys == null || DataSourceBuilder.PrimaryKeys.Count == 0)
            {
                Alert.MessageBox("列表中没有资产!");
                return;
            }
            UpdateAssetInfos(WoCode);
           pgList.BindGrid();
        }
    }
}